package com.jarich.morewore.model;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

public class Weerbericht {

	String plaatsnaam;
	double temperatuur;
	int woeid;
	String weerXml;
	XMLOutputter printer = new XMLOutputter();

	public Weerbericht() {

	}
	
	public static int getStaticWOEID(String plaatsNaam)
	{
		String urlstr = "http://where.yahooapis.com/v1/places.q('"
				+ plaatsNaam
				+ "')?appid=cGj7kzTV34F0Qj0ZU2ESMYOtlzy1gL13aL0un5CSg_f03Ax9CBjtoPQ4.ZN6WCtxuDrHA7_jLg87hBTsqubdzcNzC7afHag-";
		try {
			URL url = new URL(urlstr);
			URLConnection conn = url.openConnection();
			SAXBuilder parser = new SAXBuilder();
			Document doc = parser.build(conn.getInputStream());
			return getStaticWOEIDFromDOM(doc);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}catch (JDOMException e){
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	// Nu moet ie werken :)
	public int getWOEID(String plaatsNaam) {
		String urlstr = "http://where.yahooapis.com/v1/places.q('"
				+ plaatsNaam
				+ "')?appid=cGj7kzTV34F0Qj0ZU2ESMYOtlzy1gL13aL0un5CSg_f03Ax9CBjtoPQ4.ZN6WCtxuDrHA7_jLg87hBTsqubdzcNzC7afHag-";
		try {
			URL url = new URL(urlstr);
			URLConnection conn = url.openConnection();
			SAXBuilder parser = new SAXBuilder();
			Document doc = parser.build(conn.getInputStream());
			return getWOEIDFromDOM(doc);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}catch (JDOMException e){
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	// http://weather.yahooapis.com/forecastrss?w=729139

	public String getWeerbericht(int woeid) {
		String urlstr = "http://weather.yahooapis.com/forecastrss?w=" + woeid + "&u=c";
		try {
			URL url = new URL(urlstr);
			URLConnection conn = url.openConnection();
			SAXBuilder parser = new SAXBuilder();
			Document doc = parser.build(conn.getInputStream());
			return doc.getRootElement().getChild("channel").getChild("item").getChild("description").getContent(1).getValue().split("<a")[0];

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JDOMException e){
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static Drawable getIcon(int woeid, Context c)
	{
		String urlstr = "http://weather.yahooapis.com/forecastrss?w=" + woeid + "&u=c";
		try {
			URL url = new URL(urlstr);
			URLConnection conn = url.openConnection();
			SAXBuilder parser = new SAXBuilder();
			Document doc = parser.build(conn.getInputStream());
			String html = doc.getRootElement().getChild("channel").getChild("item").getChild("description").getContent(1).getValue();
			String imageURL = html.split("<br />")[0].split("\"")[1];
			Element item = doc.getRootElement().getChild("channel").getChild("item");
			Element yw = item.getChildren().get(5);
			//List<Element> es = item.getChildren();
			//System.out.println(es);
			String temp = yw.getAttributeValue("temp");
			System.out.println(temp);
			Drawable d = LoadImageFromWebOperations(imageURL);
			d = new TextDrawable(temp + "°C", resize(d));
			return d;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JDOMException e){
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static Bitmap getBitmapIcon(int woeid, Context c)
	{
		String urlstr = "http://weather.yahooapis.com/forecastrss?w=" + woeid + "&u=c";
		try {
			URL url = new URL(urlstr);
			URLConnection conn = url.openConnection();
			SAXBuilder parser = new SAXBuilder();
			Document doc = parser.build(conn.getInputStream());
			String html = doc.getRootElement().getChild("channel").getChild("item").getChild("description").getContent(1).getValue();
			String imageURL = html.split("<br />")[0].split("\"")[1];
			Element item = doc.getRootElement().getChild("channel").getChild("item");
			Element yw = item.getChildren().get(5);
			//List<Element> es = item.getChildren();
			//System.out.println(es);
			String temp = yw.getAttributeValue("temp");
			//System.out.println(temp);
			return textOnBitmap(bitmapFromUrl(imageURL), temp);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JDOMException e){
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	   private static Drawable resize(Drawable image) {
		    Bitmap d = ((BitmapDrawable)image).getBitmap();
		    Bitmap bitmapOrig = Bitmap.createScaledBitmap(d, 100, 100, false);
		    return new BitmapDrawable(bitmapOrig);
		}
	
	   public static Bitmap textOnBitmap(Bitmap b, String text) {
		   b = b.copy(Bitmap.Config.ARGB_8888, true);
		   Canvas c = new Canvas(b);
		  // c.clipRect(c.getClipBounds().left, c.getClipBounds().top + 15, c.getClipBounds().right, c.getClipBounds().bottom + 15, android.graphics.Region.Op.REPLACE);
		   Paint p = new Paint();
		   p.setColor(Color.BLACK);
		   p.setTextSize(20);
		   //c.drawText(text, -30, -20, p);
		   c.drawText(text + "°C", 5, 15, p);

		   return b;  
	   }
	   
	   public static Bitmap bitmapFromUrl(String url) {
		    try {
		        InputStream is = (InputStream) new URL(url).getContent();
		        Bitmap d = BitmapFactory.decodeStream(is);
		        return d;
		    } catch (Exception e) {
		    	e.printStackTrace();
		        return null;
		    }
		}   
	   
	public static Drawable LoadImageFromWebOperations(String url) {
	    try {
	        InputStream is = (InputStream) new URL(url).getContent();
	        Drawable d = Drawable.createFromStream(is, "src name");
	        return d;
	    } catch (Exception e) {
	    	e.printStackTrace();
	        return null;
	    }
	}

	/**
	 * Parsing an XML file and then playing with some basic JDOM functionality!
	 * 
	 * @param anXmlDocFile
	 */
	private void parseAndPlay() {
		// create a parser
		SAXBuilder parser = new SAXBuilder();
		try {
			// get the dom-document
			URL url = new URL("http://weather.yahooapis.com/forecastrss?w=729139&u=c");
			URLConnection conn = url.openConnection();
			Document doc = parser.build(conn.getInputStream());
			
			String s = doc.getRootElement().getChild("channel").getChild("item").getChild("description").getContent(1).getValue();

			System.out.println(s);
			
			//this.printJDom(doc);


		} catch (JDOMException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	private int getWOEIDFromDOM(Document d)
	{
		try
		{
			return Integer.parseInt(d.getRootElement().getChildren().get(0).getChildren().get(0).getContent(0).getValue());
		}
		catch(Exception e) { return 23424909; }
	}
	private static int getStaticWOEIDFromDOM(Document d)
	{
		try
		{
			return Integer.parseInt(d.getRootElement().getChildren().get(0).getChildren().get(0).getContent(0).getValue());
		}
		catch(Exception e) { return 23424909; }
	}
	
	/**
     * Using the XMLOuputer prints in the Console
     * the JDOM tree!
     * @param aJDOMdoc A JDOM Document
     * @throws java.io.IOException
     */
    private void printJDom(Document aJDOMdoc) throws IOException{
        System.out.println("<------------XML DOCUMENT------------>");
        this.printer.output(aJDOMdoc, System.out);
    }
    
    /**
     * Main Method - Program Start!
     * @param args
     */
    /*public static void main(String[] args){
        Weerbericht w = new Weerbericht();
        w.getIcon(729139);
    }*/
}
